/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import com.nanosn.polls.Controller;
import com.nanosn.utils.ClassUtility;
import com.nanosn.web.framework.rest.IRest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author selkhateeb
 */
public class RESTServlet extends HttpServlet
{

    static final long serialVersionUID = 1L;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {

        //response.setContentType("json/application");
        response.setContentType("text/plain");

        PrintWriter out = response.getWriter();

        Logger.getLogger(RESTServlet.class.getName()).log(Level.INFO, request.getRequestURI());
        Logger.getLogger(RESTServlet.class.getName()).log(Level.INFO, request.getQueryString());

        //out.write(request.getPathInfo());
        //TODO: Do I need to validate the URI??
        List<String> uri = new ArrayList<String>(Arrays.asList(request.getPathInfo().split("/")));


        //out.write(path[1]);
        while (uri.get(0).equals(""))
        {
            uri.remove(0);
        }

        String className = uri.get(0);
        uri.remove(0);

        //this.getClass().getClassLoader().getResources(className);
//        try
//        {
//            List<Class> classes = ClassUtility.GetAllClassesInJar("war:///WEB-INF/lib/polls.jar");
//            for (Class clazz : classes)
//            {
//                if (clazz.getSuperclass().equals(Controller.class) && clazz.getSimpleName().equals(className))
//                {
//                    Logger.getLogger(RESTServlet.class.getName()).log(Level.INFO, "YAAAAAAAYYYYYYYYY " + clazz.getName());
//                }
//            }
//        }
//        catch (ClassNotFoundException ex)
//        {
//            Logger.getLogger(RESTServlet.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage());
//        }
//        try
//        {
//
//            File f = new File("war:///");
//            for (String string : f.list())
//            {
//                System.out.println(string);
//            }
//        }
//        catch (Exception ex)
//        {
//            Logger.getLogger(RESTServlet.class.getName()).log(Level.SEVERE, ex.toString());
//            Logger.getLogger(RESTServlet.class.getName()).log(Level.SEVERE, "ERROR OPEING FILE IN WAR");
//        }

        IRest rest;
        try
        {
            rest = new RestFactoryImpl().CreateInstance(Class.forName(className));
            rest.setWriter(out);
            if (request.getMethod().equalsIgnoreCase("GET"))
            {
                rest.WriteResource(uri);
            }
            else if (request.getMethod().equalsIgnoreCase("POST"))
            {
                StringBuilder sb = RequestContentReader(request);

                System.out.println("sb = " + sb.toString());

                rest.Insert(sb.toString());
            }
            else if (request.getMethod().equalsIgnoreCase("PUT"))
            {
                StringBuilder sb = RequestContentReader(request);
                System.out.println("sb = " + sb.toString());

                rest.Update(uri.get(0), sb.toString());
                uri.remove(0);
            }
            else if (request.getMethod().equalsIgnoreCase("DELETE"))
            {
                StringBuilder sb = RequestContentReader(request);

                rest.Delete(uri.get(0));
                uri.remove(0);
            }
        }
        catch (Exception ex)
        {
            Logger.getLogger(RESTServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        //Query
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        //Create/Insert
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short escription";
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //Update
        processRequest(request, response);
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        processRequest(request, response);
    }

    private StringBuilder RequestContentReader(HttpServletRequest request) throws IOException
    {
        InputStream is = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try
        {
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                is.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return sb;
    }
    // </editor-fold>
}
